import os
from ultralytics import YOLO

from app.config import appLogger
from app.dependencies import singleton
from app.exception.base import BaseException
from app.utils import base2numpy
from app.resource import resource_dir
from app.utils.PhotoStandard import ErrorCode, error_msgs


# yolo接口实例
@singleton
class YoloClient:

  def __init__(self):
    model_name = "yolov11-head.pt"
    model_file_path = os.path.join(resource_dir, model_name)
    self.model = YOLO(model_file_path)


  def get_summary(self, bs64 : str):
    return self.model(base2numpy(bs64))[0].summary()


  # 获取人像头顶参数
  def get_photo_head_param(self, bs64 : str):
    image = base2numpy(bs64)
    results = self.model(image)
    # 结果有效性判定
    if not results or len(results) == 0:
      appLogger.error("head results is empty")
      raise BaseException(status_code=ErrorCode.HEAD_TOP, detail=error_msgs[ErrorCode.HEAD_TOP])

    summarys = results[0].summary()
    if not summarys or len(summarys) == 0:
      appLogger.error("head summary is empty")
      raise BaseException(status_code=ErrorCode.HEAD_TOP, detail=error_msgs[ErrorCode.HEAD_TOP])

    summary = summarys[0]
    if "box" not in summary:
      appLogger.error("head box is empty")
      raise BaseException(status_code=ErrorCode.HEAD_TOP, detail=error_msgs[ErrorCode.HEAD_TOP])

    box = summary.get("box")
    if "y1" not in box:
      appLogger.error("head box y1 is empty")
      raise BaseException(status_code=ErrorCode.HEAD_TOP, detail=error_msgs[ErrorCode.HEAD_TOP])

    y1 = box.get("y1")
    return y1



# model = YOLO("app/resource/yolov11-head.pt")
# model = YOLO("app/resource/yolov11-head-old.pt")
#
# def get_photo_head_param(bs64 : str):
#   image = base2numpy(bs64)
#   results = model(image)
#   # 结果有效性判定
#   if not results or len(results) == 0:
#     raise Exception("head results is empty")
#
#   summarys = results[0].summary()
#   if not summarys or len(summarys) == 0:
#     raise Exception("head summary is empty")
#
#   summary = summarys[0]
#   if "box" not in summary:
#     raise Exception("head box is empty")
#
#   box = summary.get("box")
#   if "y1" not in box:
#     raise Exception("head box y1 is empty")
#
#   y1 = box.get("y1")
#   return y1
